#!/bin/sh
### BEGIN INIT INFO
# Provides:          salt-api
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: REST API for Salt
# Description:       salt-api provides a REST interface to the Salt master
### END INIT INFO

# Author: Michael Prokop <mika@debian.org>

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="REST API for Salt"
NAME=salt-api
DAEMON=/usr/bin/salt-api
DAEMON_ARGS="-d"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start() {
    pid=$(pidofproc -p $PIDFILE $DAEMON)
    if [ -n "$pid" ] ; then
        log_begin_msg "$DESC already running."
        log_end_msg 0
        exit 0
    fi

    log_daemon_msg "Starting salt-api daemon: "
    start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_ARGS
    log_end_msg $?
}

do_stop() {
    log_begin_msg "Stopping $DESC ..."
    start-stop-daemon --stop --retry TERM/5 --quiet --oknodo --pidfile $PIDFILE
    RC=$?
    [ $RC -eq 0 ] && rm -f $PIDFILE
    log_end_msg $RC
}

case "$1" in
    start)
        [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
        do_start
        case "$?" in
            0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
              2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
    stop)
        [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
        do_stop
        case "$?" in
            0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
              2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
    status)
        status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
        ;;
    #reload)
        # not implemented
        #;;
    restart|force-reload)
        log_daemon_msg "Restarting $DESC" "$NAME"
        do_stop
        case "$?" in
          0|1)
              do_start
              case "$?" in
                  0) log_end_msg 0 ;;
                  1) log_end_msg 1 ;; # Old process is still running
                  *) log_end_msg 1 ;; # Failed to start
              esac
              ;;
          *)
              # Failed to stop
              log_end_msg 1
              ;;
        esac
        ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
        exit 3
        ;;
esac

exit 0
